import jwt
import time

headers = {  # 设置headers，即加密算法的配置
    "alg": "HS256",
    "typ": "JWT"
}

key = "asgfdgerher"


# 1、生成token
def generate_token(user):
    exp = int(time.time()) + 3600 * 24 * 1  # token有效期，单位秒,整体天
    payload = {
        "exp": exp,  # 该字段固定用于指定token有效期时间
        "name": "dawsonenjoy",
        "id": 123,
        "user": user,  # 自定义存储用户信息
    }
    token = jwt.encode(payload=payload, key=key, algorithm='HS256', headers=headers).decode('utf-8')
    print(token)
    return token


# 2、解码token
def untie_token(token):
    info = jwt.decode(token, key, True, algorithm='HS256')
    print(info)


time.sleep(2)


# 3、验证超时
def effective_token(token):
    try:
        info = jwt.decode(token, key, True, algorithm='HS256')
        # print(info)
        data = {
            'token': info,
            'state': 1
        }
        return data  # 未超时返回解密后token
    except jwt.PyJWTError:
        # print('超时，失效了')
        data = {
            'state': -1
        }
        return data


# 4、不校验： False，不进行校验，直接解码token
def user_token(token):
    info = jwt.decode(token, '', False, algorithm='HS256')
    # print(info)
    return info['user']


def is_token(request):  # 验证登录状态
    authorization = request.META.get('HTTP_AUTHORIZATION', None)
    if not authorization:
        return -1
    token = str(authorization).split(' ')[1]
    token_state = effective_token(token)
    if token_state['state'] == 1:  # token有效需要返回用户信息
        return user_token(token)
    else:
        # return Response({'status': -1, 'message': 'token 过期或失效！', 'data': None})
        return -1
